package com.icloud.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.icloud.common.cache.constants.CacheConstants;
import com.icloud.common.cache.service.RedisService;
import com.icloud.common.core.constant.AuthConstant;
import com.icloud.common.web.domain.UserDto;
import com.icloud.gateway.authorization.AccessTokenHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
public class ActiveUserFilter  implements GlobalFilter, Ordered {
    @Autowired
    private AccessTokenHolder accessTokenHolder;
    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String userStr = exchange.getRequest().getHeaders().getFirst(AuthConstant.USER_TOKEN_HEADER);
        if(StringUtils.isNotBlank(userStr)) {
            UserDto dto = JSONUtil.toBean(userStr, UserDto.class);
            Long userId = dto.getId();
            Long now = new Date().toInstant().getEpochSecond();
            String key = CacheConstants.CACHE_ACTIVE_USER + userId;
            redisService.set(key, now, CacheConstants.CACHE_ACTIVE_USER_VALIDITY_SECONDS);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }
}
